import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  TreeSelect,
  Modal,
  Row,
  Col,
  Radio,
} from "antd";
import {
  PlusOutlined,
  DeleteOutlined,
  RedoOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  key_find_obj,
  cash_applyu_status,
  status_code_list,
  format_time,
} from "../../utils";
import "./index.scss";

export default function MchCashApply(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [mch_ids_par, setMch_ids_par] = useState([]);
  const [com_ids_par, setCom_ids_par] = useState([]);
  const [top_amount_obj, setTop_amount_obj] = useState({});
  const [withdrawal_list, setWithdrawal_list] = useState([]);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      com_ids_par: com_ids_par,
      mch_ids_par: mch_ids_par,
    };
    setSpinning(true);
    let res = await post_axios("mch_cash_apply", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setWithdrawal_list(res.data_rows.rows);
    setTop_amount_obj(res.data);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: "公司",
      dataIndex: "company",
      align: "center",
    },
    {
      title: "商户",
      align: "center",
      dataIndex: "mch_name",
    },
    {
      title: "申请日期",
      align: "center",
      dataIndex: "apply_date",
    },
    {
      title: "提现金额",
      align: "center",
      render: (_, record) => <>{record.amount / 100}</>,
    },
    {
      title: "状态",
      align: "center",
      render: (_, record, index) => (
        <>
          {text_check(key_find_obj(record.status, cash_applyu_status, "key"))}
          {record.status == "aborded" ? <span>({record.msg})</span> : ""}
          {record.status == "banking" ? (
            <>
              <Button
                type="primary"
                shape="circle"
                icon={<RedoOutlined />}
                onClick={() => refresh_status(index, record)}
              />
            </>
          ) : (
            ""
          )}
        </>
      ),
    },
    {
      title: "收款账户",
      align: "center",
      dataIndex: "account",
    },
    {
      title: "申请人",
      align: "center",
      dataIndex: "user",
    },
    {
      title: "审核人",
      align: "center",
      dataIndex: "auditor",
    },
    {
      title: "审核日期",
      align: "center",
      dataIndex: "audittime",
    },

    {
      title: "操作",
      align: "center",
      render: (_, record) => (
        <>
          <Button onClick={() => get_detail_func(record)}>
            {t("transaction_flow.view_details")}
          </Button>
          {menu_action.indexOf("m_audit") > -1 && record.status == "add" ? (
            <Button type="primary" onClick={() => examine_click(record)}>
              审核工单
            </Button>
          ) : (
            ""
          )}
        </>
      ),
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  // 用户数据行点击
  const [clickRowKey, setClickRowKey] = useState("");
  const [clickRow, setclickRow] = useState({});

  const tableRowClick = (row) => {
    setClickRowKey(row.mch_id);
    setclickRow(row);
  };

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const initData = (page, rows) => {
    setClickRowKey("");
    setclickRow([]);
    getData(page, rows);
  };

  //获取体现关联的日结订单
  const [order_detail_show, setOrder_detail_show] = useState(false);
  const [day_settle_list, setDay_settle_list] = useState([]);
  const [bank_fee_list, setBank_fee_list] = useState([]);
  const get_detail_func = async (item) => {
    let upMsg = {
      page: 1,
      rows: 10000,
      company_id: local_company_object.id,
      company: local_company_object.company,
      com_ids_par: com_ids_par,
      mch_ids_par: mch_ids_par,
      settle_ids: item.settle_ids,
    };
    let res = await post_axios("mch_day_settle", "m_query", upMsg);
    if (!res) return;
    setDay_settle_list(res.data_rows.rows);

    await get_bank_fee_func(item);
    setOrder_detail_show(true);
  };
  const get_bank_fee_func = async (item) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      settle_ids: item.settle_ids,
      is_cash: "1",
    };
    let res = await post_axios("mch_cash_apply", "m_submit_preview", upMsg);
    if (!res) return;
    setBank_fee_list([res.data]);
  };

  // 新增体现
  const [add_day_settle_list, setAdd_day_settle_list] = useState([]);
  // 获取日结统计列表
  const get_day_settle_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      is_cash: 0,
      is_add_cash: 1,
      page: 1,
      rows: 10000,
    };
    let res = await post_axios("mch_day_settle", "m_query", upMsg);
    if (!res) return;
    setAdd_day_settle_list(res.data_rows.rows);
  };
  const [add_cash_apply_show, setAdd_cash_apply_show] = useState(false);
  const add_cash_apply = async () => {
    await get_day_settle_data();
    setAdd_cash_apply_show(true);
  };

  let select_timer = null;
  const handleSelectionChange = (keys, rows) => {
    setSelected_arr(keys);
    clearTimeout(select_timer);
    select_timer = null;
    if (keys.length === 0) {
      setAdd_cash_array([]);
    } else {
      select_timer = setTimeout(() => {
        compute_cash_number(rows);
      }, 2000);
    }
  };

  const [add_cash_array, setAdd_cash_array] = useState([]);
  const compute_cash_number = async (arr) => {
    let settle_ids = arr.map((item) => {
      return item.id;
    });
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      settle_ids,
    };
    let res = await post_axios("mch_cash_apply", "m_submit_preview", upMsg);
    if (!res) return;
    setAdd_cash_array([res.data]);
  };

  const [selected_arr, setSelected_arr] = useState([]);
  const add_cash_apply_confirm = async () => {
    let settle_ids = selected_arr.map((item) => {
      return item.id;
    });
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      settle_ids,
    };
    let res = await post_axios("mch_cash_apply", "m_submit", upMsg);
    if (!res) return;
    setAdd_cash_apply_show(false);
    search_data();
  };

  // 审核工单
  const [examine_show, setExamine_show] = useState(false);
  const [examine_status, setExamine_status] = useState("");
  const [examine_msg, setExamine_msg] = useState("");
  const examine_click = (item) => {
    setExamine_status("");
    setExamine_msg("");
    setExamine_show(true);
  };

  const examine_confirm = async () => {
    if (examine_status === "") {
      message.warning({
        content: "请选择审核状态",
      });
      return;
    }

    if (examine_status === "aborded" && examine_msg === "") {
      message.warning({
        content: "请输入驳回原因",
      });
      return;
    }

    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      id: clickRowKey,
      status: examine_status,
      msg: examine_msg,
    };
    let res = await post_axios("mch_cash_apply", "m_audit", upMsg);
    if (!res) return;
    setExamine_show(false);
    search_data();
  };

  // 刷新状态
  const refresh_status = async (index, item) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      id: item.id,
    };
    let res = await post_axios("mch_cash_apply", "m_query_banking", upMsg);
    if (!res) return;
    const newList = JSON.parse(JSON.stringify(withdrawal_list));
    withdrawal_list[index]["status"] = res.data.status;
    setWithdrawal_list(newList);
  };

  // 获取组织列表
  const [com_list, setCom_list] = useState([]);
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };

  // 筛选_获取项目列表
  const [mch_page, setMch_page] = useState(1);
  const [mch_rows, setMch_rows] = useState(20);
  const [mch_list, setMch_list] = useState([]);
  const get_mch_data = async (newPage) => {
    let upMsg = {
      page: newPage ? newPage : mch_page,
      rows: mch_rows,
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_mch",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setMch_list(res.data_rows.rows);
  };
  const mch_next_page = () => {
    setMch_page(mch_page + 1);
    setMch_ids_par([]);
    get_mch_data(mch_page + 1);
  };

  function treeNodeItem(node) {
    const { TreeNode } = TreeSelect;
    if (node.children) {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        >
          {node.children.map((child) => {
            return treeNodeItem(child);
          })}
        </TreeNode>
      );
    } else {
      return (
        <TreeNode
          value={node.com_id}
          title={node.com}
          key={node.com_id}
          selectable={node.grade === 4}
          disabled={node.grade !== 4}
        />
      );
    }
  }

  const day_settle_list_columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: "公司",
      dataIndex: "company",
      align: "center",
    },
    {
      title: "商户",
      align: "center",
      dataIndex: "mch_name",
    },
    {
      title: "销售额",
      align: "center",
      render: (_, record) => <>{record.revenue / 100}</>,
    },
    {
      title: "算法费用",
      align: "center",
      render: (_, record) => <>{(record.fee_ai / 100).toFixed(2)}</>,
    },
    {
      title: "支付费用",
      align: "center",
      render: (_, record) => <>{(record.fee_pay / 100).toFixed(2)}</>,
    },
    {
      title: "退款额",
      align: "center",
      render: (_, record) => <>{(record.refund / 100).toFixed(2)}</>,
    },
    {
      title: "结算金额",
      align: "center",
      render: (_, record) => <>{(record.settle_amount / 100).toFixed(2)}</>,
    },
    {
      title: "状态",
      align: "center",
      render: (_, record, index) => (
        <>
          {(record.status == "cash_all") === 0 ? (
            <span>未提现</span>
          ) : (
            <span>已提现</span>
          )}
        </>
      ),
    },
    {
      title: "日期",
      align: "center",
      dataIndex: "biz_date",
    },
  ];

  const bank_fee_list_columns = [
    {
      dataIndex: "",
      align: "center",
      width: 70,
      render: (_, record, index) => <>合计</>,
    },
    {
      title: "销售额",
      align: "center",
      render: (_, record) => <>{record.sale_amount / 100}</>,
    },
    {
      title: "算法费用",
      align: "center",
      render: (_, record) => <>{(record.fee_ai / 100).toFixed(2)}</>,
    },
    {
      title: "支付费用",
      align: "center",
      render: (_, record) => <>{(record.fee_pay / 100).toFixed(2)}</>,
    },
    {
      title: "提现手续费",
      align: "center",
      render: (_, record) => <>{(record.fee_bank / 100).toFixed(2)}</>,
    },
    {
      title: "退款额",
      align: "center",
      render: (_, record) => <>{(record.refund / 100).toFixed(2)}</>,
    },
    {
      title: "结算金额",
      align: "center",
      render: (_, record) => <>{(record.amount / 100).toFixed(2)}</>,
    },
  ];

  // 导出
  const [export_data_show, setExport_data_show] = useState(false);
  const [export_ranks_list, setExport_ranks_list] = useState([]);
  const export_data = async () => {
    await get_export_ranks_data();
    setExport_data_show(true);
  };
  const get_export_ranks_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      down_type: "Transaction History",
    };
    setSpinning(true);
    let res = await post_axios("task_export", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setExport_ranks_list(res.data_rows.rows);
  };

  const add_export_ranks = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      com_ids_par: com_ids_par,
      mch_ids_par: mch_ids_par,
    };
    setSpinning(true);
    let res = await post_axios("sale_flow", "m_export", upMsg);
    setSpinning(false);
    if (!res) return;
    get_export_ranks_data();
  };
  const download_export_data = (item) => {
    window.open(item.export_url);
  };
  const delete_export_data = async (item) => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      id: item.id,
      export_name: item.export_name,
    };
    setSpinning(true);
    let res = await post_axios("task_export", "m_del", upMsg);
    if (!res) return;
    setSpinning(false);
    message.warning({
      content: t("common.delete_success"),
    });
    get_export_ranks_data();
  };

  const exportRanksColumns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("operate.time"),
      align: "center",
      render: (_, record) => (
        <>{record.op_time ? format_time(record.op_time, "type_s") : ""}</>
      ),
    },
    {
      title: t("transaction_flow.file_name"),
      align: "center",
      width: 300,
      dataIndex: "export_name",
    },
    {
      title: t("transaction_flow.status"),
      align: "center",
      render: (_, record) => (
        <>{text_check(status_code_list[record.status_code])}</>
      ),
    },
    {
      title: t("transaction_flow.operation"),
      align: "center",
      render: (_, record) => (
        <>
          <Button
            size="small"
            type="primary"
            style={{
              marginRight: "10px",
            }}
            onClick={() => download_export_data(record)}
            disabled={record.status_code !== "Success"}
          >
            {t("transaction_flow.download")}
          </Button>
          <Button
            size="small"
            type="primary"
            danger
            onClick={() => delete_export_data(record)}
          >
            {t("transaction_flow.delete")}
          </Button>
        </>
      ),
    },
  ];
  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("mch_cash_apply")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70 - 150 - 80;
      setTableHeight(tableHeight);
    });
    if (user_grade < 70) {
      get_com_data();
    }
    get_mch_data();
  }, []);
  return (
    <>
      <div className="mch_cash_apply modules">
        <div className="el-col-parent">
          <Row>
            <Col span={6}>
              <div className="el-col-layout">
                <span className="el-col-text-top"> 清分中(元) </span>
                <br />
                <span className="el-col-text-amount">
                  {(top_amount_obj.can_not_cash_amount / 100).toFixed(2)}
                </span>
              </div>
            </Col>
            <Col span={6}>
              <div className="el-col-layout">
                <span className="el-col-text-top"> 提现中(元) </span>
                <br />
                <span className="el-col-text-amount">
                  {(top_amount_obj.cashing_amount / 100).toFixed(2)}
                </span>
              </div>
            </Col>
            <Col span={6}>
              <div className="el-col-layout">
                <span className="el-col-text-top"> 已提现(元) </span>
                <br />
                <span className="el-col-text-amount">
                  {(top_amount_obj.cashed_amount / 100).toFixed(2)}
                </span>
              </div>
            </Col>
            <Col span={6}>
              <div className="el-col-layout">
                <span className="el-col-text-top"> 可提现(元) </span>
                <br />
                <span className="el-col-text-amount">
                  {(top_amount_obj.can_cash_amount / 100).toFixed(2)}
                </span>
              </div>
            </Col>
          </Row>
        </div>
        <div className="screen_ipt">
          {user_grade < 70 ? (
            <div className="ipt_box ipt_box_long">
              <div className="ipt_box_title">{t("market.organization")}</div>
              <TreeSelect
                value={com_ids_par}
                treeData={com_list}
                allowClear={true}
                size="small"
                multiple
                treeCheckStrictly={true}
                fieldNames={{
                  label: "com",
                  value: "com_id",
                  children: "children",
                }}
                placeholder=" "
                treeCheckable={true}
                onChange={(newValue) => setCom_ids_par(newValue)}
              />
            </div>
          ) : (
            ""
          )}
          <div className="ipt_box ipt_box_long">
            <div className="ipt_box_title">{t("market.mch")}</div>
            <Select
              mode="multiple"
              size="small"
              placeholder=" "
              allowClear={true}
              value={mch_ids_par}
              options={mch_list}
              fieldNames={{
                label: "mch",
                value: "mch_id",
              }}
              onChange={(value) => setMch_ids_par(value)}
              onPopupScroll={(event) => {
                if (mch_list.length < mch_page * 20) {
                  console.log("没有更多项目的筛选数据了");
                  return;
                }
                const target = event.target;
                const residueHeight =
                  target.scrollHeight - target.scrollTop - target.clientHeight;
                if (residueHeight <= 50) {
                  mch_next_page();
                }
              }}
              optionFilterProp="mch"
            ></Select>
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_submit") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={add_cash_apply}
              >
                {text_check(user_power_lang["m_submit"])}
              </Button>
            ) : (
              ""
            )}
            {/* 导出 */}
            {menu_action.indexOf("m_export") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
                onClick={export_data}
              >
                {text_check(user_power_lang["m_export"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={withdrawal_list}
              size="small"
              bordered
              columns={columns}
              rowKey="id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>

      <Modal
        title="详情"
        open={order_detail_show}
        classNames={{
          body: "edit_dialog_body",
          wrapper: "edit_800_style",
        }}
        onCancel={() => setOrder_detail_show(false)}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <Table
          dataSource={day_settle_list}
          size="small"
          bordered
          columns={day_settle_list_columns}
          rowKey="id"
          virtual
          scroll={{
            y: 500,
          }}
          rowHoverable={false}
          pagination={false}
        />
        <div
          style={{
            height:
              day_settle_list.length >= 10
                ? "30px"
                : 300 - day_settle_list.length * 30 + "px",
            width: "100%",
          }}
        ></div>
        <Table
          dataSource={bank_fee_list}
          size="small"
          bordered
          columns={bank_fee_list_columns}
          rowKey="id"
          virtual
          scroll={{
            y: 100,
          }}
          rowHoverable={false}
          pagination={false}
        />
      </Modal>
      <Modal
        title="新增"
        open={add_cash_apply_show}
        classNames={{
          body: "edit_dialog_body",
          wrapper: "edit_900_style",
        }}
        onOk={add_cash_apply_confirm}
        onCancel={() => setAdd_cash_apply_show(false)}
        maskClosable={false}
        destroyOnClose={true}
      >
        <Table
          dataSource={add_day_settle_list}
          size="small"
          bordered
          columns={day_settle_list_columns}
          rowSelection={{
            type: "checkbox",
            onChange: (selectedRowKeys, selectedRows) => {
              console.log(
                `selectedRowKeys: ${selectedRowKeys}`,
                "selectedRows: ",
                selectedRows
              );
              handleSelectionChange(selectedRowKeys, selectedRows);
            },
          }}
          rowKey="id"
          virtual
          scroll={{
            y: 500,
          }}
          rowHoverable={false}
          pagination={false}
        />
        <div
          style={{
            height:
              add_day_settle_list.length >= 10
                ? "30px"
                : 300 - add_day_settle_list.length * 30 + "px",
            width: "100%",
          }}
        ></div>
        <Table
          dataSource={add_cash_array}
          size="small"
          bordered
          columns={bank_fee_list_columns}
          rowKey="id"
          virtual
          scroll={{
            y: 100,
          }}
          rowHoverable={false}
          pagination={false}
        />
      </Modal>

      <Modal
        title="审核工单"
        open={examine_show}
        classNames={{
          body: "edit_dialog_body",
        }}
        onOk={examine_confirm}
        onCancel={() => setExamine_show(false)}
        maskClosable={false}
        destroyOnClose={true}
      >
        <Radio.Group
          options={[
            {
              label: "通过",
              value: "audited",
            },
            {
              label: "驳回",
              value: "aborded",
            },
          ]}
          onChange={(e) => setExamine_status(e.target.value)}
          value={examine_status}
        />
        {examine_status == "aborded" ? (
          <div className="dialog_ipt_box">
            <div className="ipt_box_title">驳回原因</div>
            <Input
              placeholder=" "
              value={examine_msg}
              onChange={(e) => setExamine_msg(e.target.value)}
            />
          </div>
        ) : (
          ""
        )}
      </Modal>

      {/* 导出 */}
      <Modal
        title={t("transaction_flow.export")}
        open={export_data_show}
        onOk={false}
        onCancel={() => setExport_data_show(false)}
        classNames={{ body: "edit_dialog_body", wrapper: "edit_900_style" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="export_btn">
          <div className="btn_box">
            {/* 添加 */}
            <Button
              size="small"
              type="text"
              icon={<PlusOutlined style={{ color: "#1677FF" }} />}
              onClick={add_export_ranks}
            >
              {text_check(user_power_lang["m_add"])}
            </Button>
            {/* 查询 */}
            <Button
              size="small"
              type="text"
              icon={<SearchOutlined style={{ color: "#1677FF" }} />}
              onClick={get_export_ranks_data}
            >
              {text_check(user_power_lang["m_query"])}
            </Button>
          </div>
        </div>

        <div className="noPage-table" style={{ height: "300px" }}>
          <Table
            dataSource={export_ranks_list}
            size="small"
            bordered
            columns={exportRanksColumns}
            rowKey="id"
            virtual
            scroll={{
              y: 300,
            }}
            rowHoverable={false}
            pagination={false}
          />
        </div>
      </Modal>
    </>
  );
}
